<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>websocket测试</title>
</head>
<body>
    <script>
        var socket;
        if (window.WebSocket) {

          socket = new WebSocket("ws://localhost:7000/hello")
          // 相当于channelRead0， ev收到服务端回送的消息
          socket.onmessage = function (ev) {
            let responseText = document.getElementById('responseText')
            responseText.value = responseText.value + "\n" + ev.data
          }
          // 相当于连接开启
          socket.onopen = function (ev) {
            let responseText = document.getElementById('responseText')
            responseText.value = "连接开启"
          }
          // 相当于连接关闭
          socket.onclose = function (ev) {
            let responseText = document.getElementById('responseText')
            responseText.value = responseText.value + "\n"  + "连接关闭"
          }
        }else {
          alert("当前浏览器不支持WebSocket")
        }

        // 发送消息到服务端
        function send (message) {
          if (!window.socket) {
            return
          }
          if (socket.readyState === WebSocket.OPEN) {
            socket.send(message)
          }else {
            alert('连接未开启')
          }

        }
    </script>
    <form onsubmit="return false">
        <textarea name="message" style="width: 300px;height: 300px"></textarea>
        <input type="button" value="发送消息" onclick="send(this.form.message.value)">
        <textarea id="responseText" style="width: 300px;height: 300px"></textarea>
        <input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''">
    </form>
</body>
</html>